package com.newupbank.schedule.aliyun.task;


import cn.hutool.core.bean.BeanUtil;
import com.newupbank.schedule.aliyun.vo.IpInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

@Component
public class Ipv6Interface {
    private static final Logger logger = LoggerFactory.getLogger(Ipv6Interface.class);

    public IpInfoVO getNativeIpv6() {
        // 枚举所有接口
        Enumeration<NetworkInterface> enuNetworkInterface = null;
        try {
            enuNetworkInterface = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            logger.error("IPv6Interface===>printIPv6 is error!", e);
        }
        // 所有接口信息存入 ArrayList 对象
        ArrayList<NetworkInterface> arryNetworkInterface = Collections.list(enuNetworkInterface);

        // 遍历存入接口的 ArryList 对象
        for (NetworkInterface networkInterface : arryNetworkInterface) {
            // 得到一个借口给
            // 获取每个接口中的所有ip网络接口集合，因为可能有子接口
            ArrayList<InetAddress> arryInetAddress = Collections.list(networkInterface.getInetAddresses());

            // 获取接口名[wlan0]
            final String interfaceName = networkInterface.getName();

            // 遍历某个接口下的所有 IP 地址
            for (InetAddress inet : arryInetAddress) {
                // 筛选地址类型
                if (inet instanceof Inet6Address) {
                    // 列出 ipv6 地址[2409:...]
                    String strIP = inet.getHostAddress();
                    IPv6Enum[] values = IPv6Enum.values();
                    for (IPv6Enum value : values) {
                        if (value.getInetfaceName().equals(interfaceName) && strIP.startsWith(value.getStarted())) {
                            IpInfoVO ipInfoVO = new IpInfoVO();
                            copyProperties(value, ipInfoVO);
                            // 树莓派ip62409:8a56:33e4:5410:66c1:7cc7:2510:8af3%wlan0
                            if (strIP.contains("%" + value.getInetfaceName())) {
                                String[] split = strIP.split("%");
                                strIP = split[0];
                            }
                            ipInfoVO.setIp6Value(strIP);
                            return ipInfoVO;
                        }
                    }

                }
            }
        }
        return null;
    }

    public void copyProperties(Object source, Object target) {

        // BeanUtil.copyProperties(orig, dest, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        BeanUtil.copyProperties(source, target);
    }
}